/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.util.CacheManager;
import com.mol.market.common.util.DBUtils;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;
import com.mol.market.common.widget.AppListAdapter;
import com.mol.market.common.widget.AppListAdapter.ViewBinder;
import com.mol.market.common.widget.BaseActivity;

/**
 * 设置页面
 * 
 * @author andrew.wang
 * @date 2012-2-14
 */
public class PreferenceActivity extends BaseActivity implements OnItemClickListener {

    private static final String KEY_ICON = "icon";
    private static final String KEY_NAME = "name";
    private static final String KEY_SUMMARY = "summary";
    private static final String KEY_CHECKED = "checked";
    
    /** 清除缓存 */
    private static final int DIALOG_CLEAR_CACHE = 0;
    /** 清除搜索历史 */
    private static final int DIALOG_SEARCH_HISTORY = 1;
    
    // 检查用户是否更换主题

    private BroadcastReceiver mThemeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TopBar.initSkin(Session.get(context), PreferenceActivity.this);
        }
    };
    
    private ListView mList;
    private AppListAdapter mAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_preference_layout);
        
        TopBar.createTopBar(Session.get(getApplicationContext()), this,
                new View[] { findViewById(R.id.top_bar_title) }, new int[] { View.VISIBLE },
                getString(R.string.menu_setting));
        
        IntentFilter themeFilter = new IntentFilter(Constants.BROADCAST_CHANGE_THEME);
        registerReceiver(mThemeReceiver, themeFilter);

        mList = (ListView) findViewById(android.R.id.list);
        mList.setOnItemClickListener(this);
        
        // 初始化设置数据
        ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
        
        // 主题设置
        HashMap<String, Object> themeGroup = new HashMap<String, Object>();
        themeGroup.put(KEY_NAME, getString(R.string.pref_theme_settings));
        themeGroup.put(Constants.KEY_PLACEHOLDER, true);
        data.add(themeGroup);
        
        int theme = mSession.getTheme();
        boolean isDarkTheme = theme == ThemeManager.THEME_TYPE_DARK;
        
        // 深色主题
        HashMap<String, Object> darkTheme = new HashMap<String, Object>();
        darkTheme.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_theme_dark));
        darkTheme.put(KEY_NAME, getString(R.string.pref_theme_dark));
        darkTheme.put(KEY_SUMMARY, getString(R.string.pref_theme_dark_summary));
        darkTheme.put(KEY_CHECKED, isDarkTheme);
        data.add(darkTheme);
        
        // 浅色主题
        HashMap<String, Object> lightTheme = new HashMap<String, Object>();
        lightTheme.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_theme_light));
        lightTheme.put(KEY_NAME, getString(R.string.pref_theme_light));
        lightTheme.put(KEY_SUMMARY, getString(R.string.pref_theme_light_summary));
        lightTheme.put(KEY_CHECKED, !isDarkTheme);
        data.add(lightTheme);
        
        // 使用习惯
        HashMap<String, Object> favorites = new HashMap<String, Object>();
        favorites.put(KEY_NAME, getString(R.string.pref_market_settings));
        favorites.put(Constants.KEY_PLACEHOLDER, true);
        data.add(favorites);
        
        // 更新提醒
        HashMap<String, Object> updatesReminder = new HashMap<String, Object>();
        updatesReminder.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_icon_update));
        updatesReminder.put(KEY_NAME, getString(R.string.pref_market_app_update_notification));
        updatesReminder.put(KEY_SUMMARY, getString(R.string.pref_market_app_update_notification_summary));
        updatesReminder.put(KEY_CHECKED, mSession.isNotificationUpdateApps());
        data.add(updatesReminder);
        
        // 机锋推荐
        HashMap<String, Object> appPush = new HashMap<String, Object>();
        appPush.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_icon_recommend));
        appPush.put(KEY_NAME, getString(R.string.pref_market_push_app));
        appPush.put(KEY_SUMMARY, getString(R.string.pref_market_push_app_summary));
        appPush.put(KEY_CHECKED, mSession.isNotificationRecommendApps());
        data.add(appPush);
        
        // 无图模式
        HashMap<String, Object> quickMode = new HashMap<String, Object>();
        quickMode.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_icon_speed));
        quickMode.put(KEY_NAME, getString(R.string.pref_market_app_not_download_image));
        quickMode.put(KEY_SUMMARY, getString(R.string.pref_market_app_not_download_image_summary));
        quickMode.put(KEY_CHECKED, mSession.isStopDownloadImage());
        data.add(quickMode);
        
        // 自动删除
        HashMap<String, Object> autoDelete = new HashMap<String, Object>();
        autoDelete.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_icon_delete));
        autoDelete.put(KEY_NAME, getString(R.string.pref_market_app_delete_after_installation));
        autoDelete.put(KEY_SUMMARY, getString(R.string.pref_market_app_delete_after_installation_summary));
        autoDelete.put(KEY_CHECKED, mSession.isAutoDelete());
        data.add(autoDelete);
        
        // 缓存和隐私设置
        HashMap<String, Object> privacy = new HashMap<String, Object>();
        privacy.put(KEY_NAME, getString(R.string.pref_cache_settings));
        privacy.put(Constants.KEY_PLACEHOLDER, true);
        data.add(privacy);
        
        // 清除缓存
        HashMap<String, Object> clearCache = new HashMap<String, Object>();
        clearCache.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_icon_cache));
        clearCache.put(KEY_NAME, getString(R.string.pref_cache_settings_manual));
        clearCache.put(KEY_SUMMARY, getString(R.string.pref_cache_settings_manual_summary));
        data.add(clearCache);
        
        // 清除搜索历史
        HashMap<String, Object> clearSearchHistory = new HashMap<String, Object>();
        clearSearchHistory.put(KEY_ICON, getResources().getDrawable(R.drawable.pref_icon_history));
        clearSearchHistory.put(KEY_NAME, getString(R.string.pref_search_settings_title));
        clearSearchHistory.put(KEY_SUMMARY, getString(R.string.pref_search_settings_summary));
        data.add(clearSearchHistory);
        
        mAdapter = new AppListAdapter(getApplicationContext(),
                data,
                R.layout.activity_preference_checkbox_item, 
                new String[] { 
                    KEY_ICON,
                    KEY_NAME,
                    KEY_SUMMARY,
                    KEY_CHECKED }, 
                new int[] { 
                    R.id.iv_logo, 
                    R.id.tv_name,
                    android.R.id.summary, 
                    android.R.id.checkbox });
        mAdapter.setContainsPlaceHolder(true);
        mAdapter.setPlaceHolderResource(R.layout.activity_install_nessary_list_separator);
        mAdapter.setViewBinder(new ViewBinder() {

            @Override
            public boolean setViewValue(View view, Object data, int position,
                    Object textRepresentation) {

                if (position == 1 || position == 2) {
                    if (view.getId() == android.R.id.checkbox) {
                        boolean isChecked = (Boolean) textRepresentation;
                        CheckBox checkBox = (CheckBox) view;
                        checkBox.setButtonDrawable(R.drawable.switcher_v2);
                        checkBox.setChecked(isChecked);
                        return true;
                    }
                } else {
                    if (view.getId() == android.R.id.checkbox) {
                        CheckBox checkBox = (CheckBox) view;
                        checkBox.setButtonDrawable(R.drawable.switcher);
                    }
                }
                return false;
            }
        });
        mList.setAdapter(mAdapter);
    }
    
    @Override
    protected void onResume() {
        super.onResume();

    }
    
    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mThemeReceiver);
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        
        switch (id) {
        case DIALOG_CLEAR_CACHE:
            return new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(getString(R.string.pref_cache_settings_manual))
                    .setMessage(getString(R.string.pref_cache_settings_manual_dialog))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // clear the cache
                            final Context context = getApplicationContext();
                            Utils.clearCache(context);
                            CacheManager.getInstance(context).clearFromMemory(context);
                            Utils.trackEvent(context, Constants.GROUP_11,
                                    Constants.CLICK_CLEAR_CACHE);
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            
                        }
                    }).create();
        
        case DIALOG_SEARCH_HISTORY:
            
            return new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(getString(R.string.pref_search_settings_title))
                    .setMessage(getString(R.string.pref_search_settings_dialog))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            final Context context = getApplicationContext();
                            DBUtils.clearSearchHistory(context);
                            Utils.trackEvent(context, Constants.GROUP_11,
                                    Constants.CLICK_CLEAR_SEARCH_HISTORY);
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            
                        }
                    }).create();

        default:
            break;
        }
        return super.onCreateDialog(id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        
        if (arg2 == 1) {
            // 深色主题
            if (mSession.getTheme() == ThemeManager.THEME_TYPE_DARK) {
                return;
            }
            HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(arg2);
            item.put(KEY_CHECKED, true);
            HashMap<String, Object> item2 = (HashMap<String, Object>) mAdapter.getItem(2);
            item2.put(KEY_CHECKED, false);
            mSession.setTheme(ThemeManager.THEME_TYPE_DARK);
            sendBroadcast(new Intent(Constants.BROADCAST_CHANGE_THEME));
        } else if (arg2 == 2) {
            // 浅色主题
            if (mSession.getTheme() == ThemeManager.THEME_TYPE_LIGHT) {
                return;
            }
            HashMap<String, Object> item1 = (HashMap<String, Object>) mAdapter.getItem(1);
            item1.put(KEY_CHECKED, false);
            HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(arg2);
            item.put(KEY_CHECKED, true);
            mSession.setTheme(ThemeManager.THEME_TYPE_LIGHT);
            sendBroadcast(new Intent(Constants.BROADCAST_CHANGE_THEME));
        } else if (arg2 == 4) {
            // 更新通知
            HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(arg2);
            boolean isCheck = !mSession.isNotificationUpdateApps();
            item.put(KEY_CHECKED, isCheck);
            mSession.setNotificationUpdateApps(isCheck);
        } else if (arg2 == 5) {
            // 推送通知
            HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(arg2);
            boolean isCheck = !mSession.isNotificationRecommendApps();
            item.put(KEY_CHECKED, isCheck);
            mSession.setNotificationRecommendApps(isCheck);
        } else if (arg2 == 6) {
            // 无图模式
            HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(arg2);
            boolean isCheck = !mSession.isStopDownloadImage();
            item.put(KEY_CHECKED, isCheck);
            mSession.setStopDownloadImage(isCheck);
        } else if (arg2 == 7) {
            // 自动删除
            HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getItem(arg2);
            boolean isCheck = !mSession.isAutoDelete();
            item.put(KEY_CHECKED, isCheck);
            mSession.setAutoDelete(isCheck);
        } else if (arg2 == 9) {
            // 清除缓存
            showDialog(DIALOG_CLEAR_CACHE);
        } else if (arg2 == 10) {
            // 清除搜索历史
            showDialog(DIALOG_SEARCH_HISTORY);
        }
        mAdapter.notifyDataSetChanged();
    }

}
